<template>
  <el-popover
    v-model="notifyVisible"
    placement="bottom"
    width="400"
    trigger="click"
    popper-class="no-padding"
    @show="!socketNum && (notifyVisible = false)">
    <div class="YNotificationPopover">
      <el-card v-for="(item, i) in socketValue" :key="i" shadow="hover" @click.native="toPage(item)">
        <div slot="header">
          <span>{{flagMap[item.flag]['title']}}</span>
          <span class="el-badge__content">{{item.num}}</span>
        </div>
        <div>{{item.message}}</div>
      </el-card>
    </div>
    <el-badge slot="reference" class="YNotification" :value="socketNum" :max="99" :hidden="!socketNum">
      <i class="el-icon-bell"></i>
    </el-badge>
  </el-popover>
</template>

<script>
const flagMap = {
  adoptOrder:{
    title: '购买订单',
    route: 'adoptOrderList'
  },
  adopted:{
    title: '已购买',
    route: 'adoptedList'
  },
  uploadProof:{
    title: '收款证明',
    route: 'adoptOrderList'
  },
  waitConfirm:{
    title: '确认支付',
    route: 'adoptOrderList'
  },
  mallPayOrder:{
    title: '商品发货',
    route: 'goodsOrderList'
  },
  mallCancelPayOrder:{
    title: '商品退款',
    route: 'goodsOrderList'
  },
  mallApplyReturnOrder:{
    title: '商品售后',
    route: 'chargebackApply'
  }
}
export default {
  name: "YNotification",
  inject: ['__GLOBAL'],
  data(){
    return{
      flagMap,
      tenantId: '',
      randomCode: localStorage.Authorization,//socket随机值，暂时取token
      titleInterval: null,//title闪动效果
      heartInterval: null,//心跳
      notifyVisible: false,
      socketValue: [],//websocket返回的value
    }
  },
  computed:{
    socketNum(){
      return this.socketValue.reduce((total, item) => total + item.num, 0);
    }
  },
  mounted() {
    // this.tenantId = (this.$$getUserInfo())?.tenantId;
    // if(this.tenantId){
    //   this.initWebSocket();
    // }else{
    //   this.$message({
    //     type: 'warning',
    //     message: "未获取到用户信息，请刷新重试"
    //   });
    // }
  },
  methods: {
    initWebSocket() {
      //将WebSocket初始化在window环境中
      this.clearTitleInterval();
      if (window.WebSocket) {
        try{
          let protocol = location.protocol === 'https:' ? 'wss' : 'ws';
          this.closeWebSocket();
          const host = process.env.NODE_ENV === 'production' ? 'native.imflea.com:8000' : 'iampeiyuan.com';
          window.webSocket = new WebSocket(`${protocol}://${host}/websocket/${this.tenantId}/${this.randomCode}`);
          window.webSocket.onerror = () => {
            this.reconnectWebSocket();
          }
          window.webSocket.onclose = () => {
            this.reconnectWebSocket();
          }
          window.webSocket.onopen = () => {
            this.initHeartBeat();
          }
          window.webSocket.onmessage = ({data}) => {
            if(data !== this.randomCode){
              try{
                this.$set(this, 'socketValue', JSON.parse(data));
              }catch(e){
                this.$message({
                  type: 'warning',
                  message: "通知数据异常，请联系管理员"
                });
                console.log("异常数据：" + data);
              }
            }
            this.$nextTick(() => {
              if(this.socketNum > 0){
                if(!this.titleInterval){
                  this.titleInterval = setInterval(() => {
                    if(document.title === '\u200E'){
                      document.title = '【新消息】' + this.__GLOBAL.TITLE;
                    }else{
                      document.title = '\u200E';
                    }
                  }, 500)
                }
              }else{
                this.clearTitleInterval();
              }
            })
          }
        }catch(e){
          this.reconnectWebSocket();
        }
      }
    },
    initHeartBeat(){
      this.heartInterval = setInterval(() => {
        window.webSocket?.send(this.randomCode);
      }, 20000)
    },
    reconnectWebSocket(){
      setTimeout(() => {
        console.log('------------------------------websocket连接重试---------------------------------')
        this.initWebSocket();
      }, 2000)
    },
    toPage({flag}){
      this.$router.push({name: flagMap[flag].route});
      this.notifyVisible = false;
    },
    clearTitleInterval(){
      !!this.titleInterval && clearInterval(this.titleInterval);
      this.titleInterval = null;
      document.title = this.__GLOBAL.TITLE;
    },
    closeWebSocket(){
      clearInterval(this.heartInterval);
      this.heartInterval = null;
      if(window.webSocket){
        window.webSocket.onerror = () => {};
        window.webSocket.onclose = () => {};
        window.webSocket.close();
        delete window.webSocket;
      }
    }
  },
  beforeDestroy() {
    this.clearTitleInterval();
    this.closeWebSocket();
  }
}
</script>

<style scoped lang="less">
.YNotificationPopover{
  max-height: 351px;
  overflow-y: auto;
  padding: 12px;
  >.el-card{
    border-color: @table-bolder-color;
    cursor: pointer;
    &:not(:first-child){
      margin-top: 10px;
    }
    /deep/ .el-card__header{
      padding: 10px 20px;
      background: @table-header-color;
      font-weight: bold;
    }
    .el-badge__content{
      margin-left: 10px;
      border: 0;
      font-weight: normal;
      &:before{
        content: '+';
      }
    }
  }
}
.YNotification{
  cursor: pointer;
  >i{
    color: #fff;
    font-size: 24px;
  }
  /deep/ sup{
    border: 0;
  }
}
</style>
